package com.bootdo.common.task;

import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.ordertrace.model.LgsOrderStatusUpdate;
import com.bootdo.lgs.ordertrace.model.UnCheckCondition;
import com.bootdo.lgs.ordertrace.service.OrderTraceService;
import com.bootdo.oa.domain.NotifyDO;
import com.bootdo.oa.service.NotifyService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class LgsTrackKuai100Job implements Job {

    private static final Logger logger = LoggerFactory.getLogger(LgsTrackKuai100Job.class);

    @Autowired
    private OrderTraceService orderTraceService;

    @Resource
    private NotifyService notifyService;

    private void before() {
        System.out.println("=========任务开始执行===========");
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        before();
        System.out.println("更新 跟踪信息 开始：" + System.currentTimeMillis());
        // 先查询出来目前已发货（状态5）还未签收的订单（前80个，按id排序、最新的订单排序在前面）（排除特殊的物流公司：今朝阳）
        UnCheckCondition condition = new UnCheckCondition();
        condition.setLimitCnt(80);
        List<LgsOrder> lgsOrders = orderTraceService.getUnCheckOrderTrace(condition);
        // 如果未签收订单为空 结束任务
        if (lgsOrders == null || lgsOrders.isEmpty())
            return;
        // 循环 对这些订单 发起请求获取物流跟踪信息
        List<LgsOrderStatusUpdate> lgsOrderStatusUpdateList = new ArrayList<>();//批量更新物流状态
        List<Long> orderIds = new ArrayList<>(); //批量删除订单跟踪信息 的订单id
        List<Map> orderTraceList = new ArrayList<>();//查询到的最新的跟踪信息
        System.out.println("准备更新物流信息：");
        List<LgsOrder> notifyItems = Lists.newArrayList();
        Date now = new Date();
        Date oneDayAgo = DateUtils.addDays(now, -1);
        Date oneMonthAgo = DateUtils.addMonths(now, -1);
        for (LgsOrder lgsOrder : lgsOrders) {
            // 获取的物流跟踪信息list为空时 结束本次循环continue
            List<Map> list = orderTraceService.getListFromRemote(lgsOrder.getLgs_company_cd(), lgsOrder.getLgs_track_number().trim(), lgsOrder.getId());
            Date bindDate = parseFTime(lgsOrder.getBind_date());
            if (list == null || list.isEmpty()) {
                if (oneDayAgo.compareTo(bindDate) > 0 && oneMonthAgo.compareTo(bindDate) < 0) {
                    notifyItems.add(lgsOrder); // 超过一天无物流信息告警
                }
                continue;
            } else {
                if (oneDayAgo.compareTo(parseFTime(MapUtils.getString(list.get(0), "ftime"))) > 0 && oneMonthAgo.compareTo(bindDate) < 0) {
                    notifyItems.add(lgsOrder); // 超过一天物流信息未更新告警
                }
            }

            orderIds.add(lgsOrder.getId());
            orderTraceList.addAll(list);
            // 如果签收状态为已签收、更新订单为已签收状态7
            if ("1".equals(list.get(0).get("ischeck"))) {
                LgsOrderStatusUpdate lgsOrderStatusUpdate = new LgsOrderStatusUpdate();
                lgsOrderStatusUpdate.setLgs_status("7");
                lgsOrderStatusUpdate.setId(lgsOrder.getId());
                lgsOrderStatusUpdateList.add(lgsOrderStatusUpdate);
            }
        }

        // 物流跟踪信息告警
        logger.info("there are {} orders need to notifying!", notifyItems.size());
        notifyItems.forEach(item -> {
            NotifyDO notifyDO = new NotifyDO();
            notifyDO.setType("3");
            notifyDO.setTitle("【物流跟踪信息告警】");
            notifyDO.setContent("系统检测到运单号【" + item.getLgs_track_number() + "】超24小时，未更新物流跟踪信息，请予核实！");
            notifyService.notifyOrderTrace(item.getId(), item.getLgs_company_cd(), notifyDO);
        });

        // 封装数据到对象、更新订单的物流跟踪信息
        orderTraceService.batchRefreshOrderTrace(lgsOrderStatusUpdateList, orderIds, orderTraceList);//更新物流跟踪信息
        System.out.println("更新 跟踪信息 结束：" + System.currentTimeMillis());
        after();
    }

    private Date parseFTime(String dateStr) {
        Date date;
        try {
            date = DateUtils.parseDate(dateStr, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-ddTHH:mm:ss");
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid date format!", e);
        }

        return date;
    }

    private void after() {
        System.out.println("==========任务结束执行============");
    }

}
